/**
 * 获取客户端真实IP
 * 
 * @param {*} request 
 */
function getClientIp(request) {
    return request.headers['x-forwarded-for'] ||
        request.connection.remoteAddress ||
        request.socket.remoteAddress ||
        request.connection.socket.remoteAddress || ''
            .match(/\d+.\d+.\d+.\d+/).join('.');
}

/**
 * 获取客户端UA字符串
 * 
 * @param {*} request 
 */
function getUAString(request) {
    return request.headers['user-agent']
}

/**
 * 获取客户端设备类型
 * 
 * @param {*} request 
 */
function getDeviceType(request) {
    let ua = getUAString(request), $ = {};

    if (/mobile/i.test(ua))
        $.Mobile = true;

    if (/like Mac OS X/.test(ua)) {
        $.iOS = /CPU( iPhone)? OS ([0-9\._]+) like Mac OS X/.exec(ua)[2].replace(/_/g, '.');
        $.iPhone = /iPhone/.test(ua);
        $.iPad = /iPad/.test(ua);
    }

    if (/Android/.test(ua))
        $.Android = /Android ([0-9\.]+)[\);]/.exec(ua)[1];

    if (/webOS\//.test(ua))
        $.webOS = /webOS\/([0-9\.]+)[\);]/.exec(ua)[1];

    if (/(Intel|PPC) Mac OS X/.test(ua))
        $.Mac = /(Intel|PPC) Mac OS X ?([0-9\._]*)[\)\;]/.exec(ua)[2].replace(/_/g, '.') || true;

    if (/Windows NT/.test(ua))
        $.Windows = /Windows NT ([0-9\._]+)[\);]/.exec(ua)[1];

    let deviceTypeString = ''
    for (const item in $) {
        deviceTypeString += item + ' '
    }

    return deviceTypeString;
}

module.exports = {
    getClientIp, getUAString, getDeviceType
}
